import { ForbiddenException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, type Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { Role } from '../role/entities/role.entity';
import { SignupUserDto } from '../auth/dto/signup-user.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Role)
    private readonly rolesRepository: Repository<Role>,
  ) {}

  findAll() {
    return this.userRepository.find();
  }

  async find(username: string, id?: number) {
    const user = await this.userRepository.findOne({
      where: [{ username }, { id }],
      relations: {
        roles: true, // eager loading
      },
    });

    return user;
  }

  async create(userDto: SignupUserDto) {
    if (
      !userDto.roles ||
      !Array.isArray(userDto.roles) ||
      userDto.roles.some((role) => typeof role !== 'number')
    ) {
      throw new ForbiddenException('用户的角色类型必传，且必须是一个数字数组');
    }

    if (!userDto.username || !userDto.password) {
      throw new ForbiddenException('用户名密码不能为空');
    }

    const roles = await this.rolesRepository.find({
      where: {
        id: In(userDto.roles),
      },
    });

    const user = await this.userRepository.create({ ...userDto, roles });

    if (!user) {
      throw new ForbiddenException('用户创建失败');
    }

    return this.userRepository.save(user);
  }

  remove(id: number) {
    return this.userRepository.delete(id);
  }

  findProfile(id: number) {
    return this.userRepository.findOne({
      where: {
        id,
      },
      relations: {
        profile: true,
      },
    });
  }
}
